package com.gitee.dolt.boot.lock;

import cn.hutool.core.util.StrUtil;
import com.gitee.dolt.annotation.lock.SysLock;
import com.gitee.dolt.core.exception.InternalServerException;
import com.gitee.dolt.core.lock.DistributedLock;
import com.gitee.dolt.core.util.SpelUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;

/**
 * SysLock锁切面
 *
 * @author LYH
 */
@RequiredArgsConstructor
@Slf4j
@Aspect
public class LockAspect {
    @Autowired(required = false)
    private DistributedLock distributedLock;

    @Pointcut("@annotation(com.gitee.dolt.annotation.lock.SysLock)")
    public void lockAspect() {

    }

    @Around("lockAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        if (distributedLock == null) {
            throw new InternalServerException("系统尝试使用锁，但实际无锁实现");
        }
        SysLock lockAnnotation = getTargetAnnotation(joinPoint);
        if (lockAnnotation == null) {
            return joinPoint.proceed();
        }
        Signature signature = joinPoint.getSignature();
        String key = lockAnnotation.value();
        if (StrUtil.isEmpty(key)) {
            if (signature instanceof MethodSignature) {
                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                key = StrUtil.join(joinPoint.getTarget().getClass().getName(), methodSignature.getName(), StrUtil.COLON);
            } else {
                key = joinPoint.getTarget().getClass().getName();
            }
        }
        if (signature instanceof MethodSignature) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            key = SpelUtils.getValBySpEL(key, methodSignature.getMethod(), joinPoint.getArgs());
        }
        if (StrUtil.isEmpty(key)) {
            throw new InternalServerException("锁值为空");
        }
        log.debug("正在执行锁，key：{}", key);
        boolean lock = distributedLock.lock(key);
        if (!lock) {
            log.debug("获取锁失败，key：{}", key);
            throw new InternalServerException("系统繁忙");
        }
        try {
            return joinPoint.proceed();
        } finally {
            log.debug("正在释放锁，key：{}", key);
            distributedLock.releaseLock(key);
        }
    }

    private SysLock getTargetAnnotation(ProceedingJoinPoint joinPoint) {
        SysLock lockAnnotation = null;
        if (joinPoint.getSignature() instanceof MethodSignature) {
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            if (method != null) {
                lockAnnotation = method.getAnnotation(SysLock.class);
            }
        }
        return lockAnnotation;
    }
}
